package com.itsu.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itsu.dao.CompanyDao;
import com.itsu.domain.Company;
import com.itsu.service.CompanyService;
import com.itsu.utils.MapperUtils;

import java.util.List;

public class CompanyServiceImpl implements CompanyService {

    private CompanyDao mapper;

    @Override
    public void save(Company company) {
        try {
            mapper = MapperUtils.getMapper(CompanyDao.class);
            mapper.save(company);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
             MapperUtils.close();
        }
    }

    @Override
    public void delete(Company company) {
        try {
            mapper = MapperUtils.getMapper(CompanyDao.class);
            mapper.delete(company);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public void update(Company company) {
        try {
            mapper = MapperUtils.getMapper(CompanyDao.class);
            mapper.update(company);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public Company findById(String id) {
        try {
            mapper = MapperUtils.getMapper(CompanyDao.class);
            Company company = mapper.findById(id);
            return company;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public List<Company> findAll() {
        try {
            mapper = MapperUtils.getMapper(CompanyDao.class);
            List<Company> companyList = mapper.findAll();
            return companyList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public PageInfo<Company> findAll(int pageNum, int pageSize) {
        try {
            mapper = MapperUtils.getMapper(CompanyDao.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Company> all = mapper.findAll();
            PageInfo<Company> companyPageInfo = new PageInfo<>(all);
            return companyPageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }
}
